﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;

namespace testList2
{
    class Program
    {
        static void Main(string[] args)
        {
            //原始数据
            List<person> p = new List<person>();
            p.Add(new person() { id = 1, name = "zhangsan", age = "15", parentid = 0, chilren = new List<person>() });
            p.Add(new person() { id = 8, name = "gaochao", age = "22", parentid = 0, chilren = new List<person>() });
            p.Add(new person() { id = 6, name = "zzy", age = "45", parentid = 0, chilren = new List<person>() });
            p.Add(new person() { id = 7, name = "lizhun", age = "55", parentid = 0, chilren = new List<person>() });
            p.Add(new person() { id = 2, name = "jay", age = "65", parentid = 1, chilren = new List<person>() });
            p.Add(new person() { id = 3, name = "tom", age = "14", parentid = 1, chilren = new List<person>() });
            p.Add(new person() { id = 4, name = "reven", age = "12", parentid = 2, chilren = new List<person>() });
            p.Add(new person() { id = 5, name = "marry", age = "5", parentid = 4, chilren = new List<person>() });

            //树结构数据
            List<person> p2 = new List<person>();
            //1.取顶级元素
            for (int i = 0; i < p.Count; i++)
            {
                if (p[i].parentid==0)
                {
                    p2.Add(p[i]);
                }
            }
            //2.递归生成树机构
            for (int i = 0; i < p2.Count; i++)
            {
                p2[i] = creatTree(p2[i], p);
            }

            string result = JsonConvert.SerializeObject(p2);
        }

        //递归方法
        private static person creatTree(person parent,List<person> all)
        {
            for (int i = 0; i < all.Count; i++)
            {
                if (parent.id==all[i].parentid)
                {
                    all[i]=creatTree(all[i], all);
                    parent.chilren.Add(all[i]);
                }
            }
            return parent;
        }
    }

    //模拟类
    class person
    {
        public int id { get; set; }

        public string name { get; set; }

        public string age { get; set; }

        public int parentid { get; set; }

        public List<person> chilren { get; set; }
    }
}
